package com.wjw.java.map;

import java.util.Comparator;
import java.util.TreeMap;

/**
 * TreeMap是Map接口的实现类
 */
public class Detail_TreeMap {
    public static void main(String[] args) {
        //1.使用无参构造,comparator = null;
        TreeMap<String,String> treeMap = new TreeMap<>();
        treeMap.put("bb","宝贝");
        treeMap.put("a","啊啊啊");
        treeMap.put("ccc","冲冲冲");
        treeMap.put("ddd","打断点");
        System.out.println(treeMap);

        System.out.println("------------------------------------");

        //2.键(key)排序,传入Comparator比较器
        TreeMap<String,String> treeMap2 = new TreeMap<>(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                //return o1.compareTo(o2);//按abcd排序
                return o1.length() - o2.length();//按字符串的长度排序,此时新增的时候,长度为1/2/3/4的字符串,换替换value
            }
        });
        treeMap2.put("bb","宝贝");
        treeMap2.put("a","啊啊啊");
        treeMap2.put("ccc","冲冲冲");
        treeMap2.put("ddd","打断点");//因为ccc和ddd的长度一样(key长度一样),就会将ccc的value替换为ddd的value
        System.out.println(treeMap2);
    }
}
